package com.example.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

open class BaseViewModel:ViewModel() {

    /**
     * 网络请求
     * s:网络请求接口
     * success:响应成功时把结果回调回去
     */
    fun<T> httpRequest(s:suspend ()-> Res<T>,success:(T)->Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if(res.code == 200) {
                    success(res.data)
                }else {
                    Log.i("lr",res.message)
                }
            }catch (e:Exception) {
                Log.i("lr",e.message.toString())
            }
        }
    }

    fun toBody(item:Any):RequestBody{
        val json = Gson().toJson(item)
        return RequestBody.create("application/json".toMediaTypeOrNull(), json)
    }
}